package yhao.infra.feature.solr.local.core.stats;

import org.apache.solr.client.solrj.SolrQuery;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 查询条件
 */
public class StatsQueryInfo {
    private List<StatsQueryParam> statsParams;

    /**
     * @param statsFields 统计查询的字段
     */
    public StatsQueryInfo(String[] statsFields) {
        statsParams = new ArrayList<>();
        for(String field:statsFields){
            statsParams.add(new StatsQueryParam(field));
        }
    }

    /**
     * @param statsParams 统计查询的字段
     */
    public StatsQueryInfo(List<StatsQueryParam> statsParams) {
        this.statsParams = statsParams;
    }

    public void addFacetsToAll(Set<String> statsFacets){
        if(statsFacets==null || statsFacets.size()==0){
            return;
        }
        for(StatsQueryParam param:statsParams){
            param.getFacets().addAll(statsFacets);
        }
    }

    public void addFacets(String statsField, Set<String> statsFacets){
        if(statsFacets==null || statsFacets.size()==0){
            return;
        }
        StatsQueryParam param = null;
        for(StatsQueryParam p:statsParams){
            if(p.getFiled().equals(statsField)){
                param = p;
                break;
            }
        }
        if(param!=null){
            param.getFacets().addAll(statsFacets);
        }
    }

    public void makeStatsIndex(SolrQuery solrQuery) {
        for(StatsQueryParam entry:statsParams){
            solrQuery.addGetFieldStatistics(entry.getFiled());
            if(entry.getFacets()!=null && entry.getFacets().size()>0){
                solrQuery.addStatsFieldFacets(entry.getFiled(), entry.getFacets().toArray(new String[0]));
            }
            if(entry.getCalcDistinct()!=null){
                solrQuery.addStatsFieldCalcDistinct(entry.getFiled(),entry.getCalcDistinct());
            }
        }
    }
}
